package com.warthur.vertx.demo.handler;

import com.warthur.vertx.demo.common.enums.ErrorCode;
import com.warthur.vertx.demo.common.enums.HttpStatus;
import com.warthur.vertx.demo.common.utils.ResponseUtils;
import io.vertx.ext.web.RoutingContext;
import lombok.extern.slf4j.Slf4j;

/**
 * @author warthur
 * @date 2019/10/10
 */
@Slf4j
public class ExceptionHandler {

    public static void exception(RoutingContext context) {

        log.error("系统异常 [ statusCode:{} message: {}]", context.statusCode(), context.failure());

        String message = ErrorCode.REQUEST_ERROR.getMsg();
        int statusCode = HttpStatus.INTERNAL_SERVER_ERROR.value();
        HttpStatus httpStatus = HttpStatus.resolve(context.statusCode());
        if (httpStatus != null) {
            statusCode = context.statusCode();
            message = httpStatus.getReasonPhrase();
        }

        if (context.failure() != null) {
            message = context.failure().getMessage();
        }

        context.response().setStatusCode(statusCode);

        ResponseUtils.build(context)
                .statusCode(statusCode)
                .message(message)
                .body();
    }
}
